//
//  ReplaceDriveViewController.m
//  JxCarios
//
//  Created by xcq on 15/1/29.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "ReplaceDriveViewController.h"
#import "customPaopaoView.h"
#import "RextExtends.h"
static NSString *cellStr = @"replaceDrive";
#define CELLHEIGHT 88
#define DIC_TYPE @"travel"

#define INTCOVERTOSTR(value) [NSString stringWithFormat:@"%ld", value]


@interface ReplaceDriveViewController ()

@end

@implementation ReplaceDriveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currenIndex = 1;
    _pageCount = 0;
    _refreshSucc = NO;
    [self initAbout];
    [self initMapView];
    [self location];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    if (_mapView) {
        _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放

    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    dex = 0;
}
//
//"CHECK_STATE" = yes;
//"ERR_NUM" = "<null>";
//"GOOD_NUM" = "<null>";
//ID = 283;
//LAT = "30.509969";
//LON = "114.413642";
//MINPRICE = "10.00";
//"SELLER_NUMBER" = 0;
//"SERVICE_TYPE" = travel;
//SFZ = 3693;              距离
//"SHOP_ADDR" = "\U5357\U660c\U53bf\U83b2\U5858\U9547\U83b2\U897f\U8def2056\U53f7";
//"SHOP_LOGO" = "http://seller.clejw.com/upload/image/201412/22dec94c-a19b-4431-a89b-89852c15d3bf.jpg";
//"SHOP_NAME" = "\U5357\U660c\U53bf\U51ef\U946b\U6c7d\U8f66\U8def\U6551";
- (void)initDataSource {
    if (!_requestDataSouce) {
        _requestDataSouce = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    
    _requestDataSouce.dic_type = DIC_TYPE;
    _requestDataSouce.lon = [NSString stringWithFormat:@"%f",_currenLocation.longitude];
    _requestDataSouce.lat = [NSString stringWithFormat:@"%f",_currenLocation.latitude];
    _requestDataSouce.page = INTCOVERTOSTR(_currenIndex);
    _tableView.tableHeaderView = [UIView new];
    [_requestDataSouce carAroundInfo:^(id result) {
       
        NSLog(@"%@",result);
        _tableDataSource = [NSMutableArray arrayWithArray:[(NSDictionary *)result objectForKey:@"sellerlist"]];
        _pageCount = [[(NSDictionary *)result objectForKey:@"totalpages"] integerValue];
        [_tableView reloadData];
        _tableView.hidden = NO;
        _mapView.hidden = NO;
        [self startDrawAnnotation];
    }anfFail:^(id result) {
         
    }];
}

- (void)startDrawAnnotation {
    if (!_annotationArr) {
        _annotationArr = [NSMutableArray new];
    }
    if (!_paoPaoArr) {
        _paoPaoArr = [NSMutableArray new];
    }
    NSMutableArray *temp = nil;
    if (_refreshSucc) {
        temp = [_refreshData mutableCopy];
    }else{
        temp = [_tableDataSource mutableCopy];
    }
    
    for (NSDictionary *dic in temp) {
        BMKPointAnnotation *point = [[BMKPointAnnotation alloc] init];
        CLLocationCoordinate2D pointCoor = CLLocationCoordinate2DMake([[dic objectForKey:@"LAT"] doubleValue],  [[dic objectForKey:@"LON"] doubleValue]);
        point.coordinate = pointCoor;
        point.title = [dic objectForKey:@"SHOP_NAME"];
        [_annotationArr addObject:point];
        
        customPaopaoView *paopao = [customPaopaoView getInstance];
        [paopao.photo setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"SHOP_LOGO"]] placeholderImage:nil options:SDWebImageProgressiveDownload ];
        paopao.name = [dic objectForKey:@"SHOP_NAME"];
        [_paoPaoArr addObject:paopao];
    }
     [_mapView setRegion:BMKCoordinateRegionMake(_currenLocation, BMKCoordinateSpanMake(0.3, 0.3)) animated:YES];
    if (_annotationArr.count > 0 && _paoPaoArr.count == _annotationArr.count) {
       
        [_mapView addAnnotations:_annotationArr];
    }
}

- (void)initMapView {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        self.locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
    }
    _mapView = [[BMKMapView alloc] initWithFrame:(CGRect){{0,64},{CGRectGetWidth([RextExtends getScreenFrame]) , CGRectGetHeight([RextExtends getScreenFrame]) - 64}}];
    _mapView.delegate = self;
    _mapView.hidden = YES;
    _mapView.mapType = BMKMapTypeStandard;
    [self.view addSubview:_mapView];
    [self.view sendSubviewToBack:_mapView];
}

- (void)initAbout{
    REGISTCELL(@"ReplaceDriveTableViewCell", cellStr);
    self.title = @"代驾";
    _tableView.tableFooterView = [UIView new];
    [_tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:@selector(navigationLeftBtnAction) andCustom:NO];
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setFrame:CGRectMake(15, 5.0f, 60, 30)];
    [_rightBtn setTitle:@"地图" forState:UIControlStateNormal];
    [_rightBtn setTitle:@"列表" forState:UIControlStateSelected];
    [_rightBtn addTarget:self action:@selector(changeVcSHowView:) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    
}

- (void)footerRefresh{
    if (_refreshData) {
        _refreshData = nil;
    }
    
    if (_pageCount <= _currenIndex) {
        [self.view makeToast:@"没有更多数据了哦"];
        [_tableView footerEndRefreshing];
        return;
    }
    _currenIndex ++;
    _requestDataSouce.dic_type = DIC_TYPE;
    _requestDataSouce.lon = [NSString stringWithFormat:@"%f",_currenLocation.longitude];
    _requestDataSouce.lat = [NSString stringWithFormat:@"%f",_currenLocation.latitude];
    _requestDataSouce.page = INTCOVERTOSTR(_currenIndex);
    _tableView.tableHeaderView = [UIView new];
    [_requestDataSouce carAroundInfo:^(id result) {
        
        NSLog(@"%@",result);
         NSArray *arrar = [(NSDictionary *)result objectForKey:@"sellerlist"];
        _refreshData = [NSMutableArray arrayWithArray:arrar];
        [_tableDataSource addObjectsFromArray:arrar];
        [_tableView reloadData];
        _refreshSucc = YES;
        [_tableView footerEndRefreshing];
        [self startDrawAnnotation];
    }anfFail:^(id result) {
        _refreshSucc = NO;
        _currenIndex --;
        [_tableView footerEndRefreshing];
    }];
}



- (void)location{
    if ([Common currenCity] && [[Common currenCity] customObjectForkey:@"location"]) {
        _currenLocation.latitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lat"] doubleValue];
        _currenLocation.longitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lon"] doubleValue];
        _mapView.showsUserLocation = YES;
        [_mapView setRegion:BMKCoordinateRegionMake(_currenLocation, BMKCoordinateSpanMake(0.3, 0.3)) animated:YES];
        [self initDataSource];
        return;
    }
    if (!self.locService) {
        self.locService = [[LocationGetObj alloc] init];
    }
    self.locService.delegate = self;
    [self.locService startLocation];
}
//实现相关delegate 处理位置信息更新

- (void)getLocationSuccess:(BMKUserLocation *)userLocation{
    _currenLocation = userLocation.location.coordinate;
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _mapView.showsUserLocation = YES;
    [_mapView setRegion:BMKCoordinateRegionMake(_currenLocation, BMKCoordinateSpanMake(0.3, 0.3)) animated:YES];
    [self initDataSource];
    
}

- (void)getLocationFail:(NSError *)error{
    TOASTSHOW(@"定位失败,无法获取列表");
}
 


- (void)changeVcSHowView:(UIButton *)sender{
    _rightBtn.selected = !_rightBtn.selected;
    if (_rightBtn.selected) { //地图
        [self.view bringSubviewToFront:_mapView];
    }else{
        
        [self.view bringSubviewToFront:_tableView];
    }
}


#pragma mark - tableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  _tableDataSource.count <= 0 ? 0 : _tableDataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ReplaceDriveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr forIndexPath:indexPath];
    cell.price.hidden = NO;
     cell.info = [_tableDataSource objectAtIndex:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CELLHEIGHT;
}


- (void)navigationLeftBtnAction{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ReplaceDetailTableViewController*  _detailTable = [[ReplaceDetailTableViewController alloc] init];
    _detailTable.sellerid = [[_tableDataSource objectAtIndex:indexPath.row] objectForKey:@"ID"];
    _detailTable.distance = [[_tableDataSource objectAtIndex:indexPath.row] objectForKey:@"SFZ"];

    [self.navigationController pushViewController:_detailTable animated:YES];
}

#pragma  mark - mapView Delegate 
static int dex = 0;
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    if (annotation == _location) {
        
        BMKPinAnnotationView *view = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"location"];
        view.pinColor = BMKPinAnnotationColorRed;
        return view;
    }
    
    static NSString *annotationIdentifier = @"bmk";
    BMKPinAnnotationView *anntationView = nil;
    if (anntationView == nil) {
        anntationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
    }
    if (anntationView.paopaoView != nil) {
        anntationView.paopaoView = nil;
    }
    anntationView.pinColor = BMKPinAnnotationColorPurple;
    anntationView.tag = 300 + dex;
    anntationView.paopaoView = [self productionPaoPaoView];
    

    dex ++;
    if(dex == _paoPaoArr.count){
        dex = 0;
    }
        return anntationView;
 }

- (BMKActionPaopaoView *)productionPaoPaoView{
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 170, 55)];
    view1.userInteractionEnabled = YES;
    [view1 setBackgroundColor:[UIColor blackColor]];
    [view1 setAlpha:0.8];
    view1.layer.cornerRadius = 5.0f;
    view1.layer.masksToBounds = YES;
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(5,6, 41, 41)];
    img.layer.cornerRadius = 3.0f;
    img.layer.masksToBounds = YES;
    [img setImageWithURL:[[_tableDataSource objectAtIndex:dex] objectForKey:@"SHOP_LOGO"] placeholderImage:nil];
    UITextView *text =nil;
    NSString *labelStr = [[_tableDataSource objectAtIndex:dex] objectForKey:@"SHOP_NAME"];
    CGSize  labelsize = CGSizeZero;
    labelsize = [labelStr sizeWithFont:[UIFont systemFontOfSize:13]
                     constrainedToSize:CGSizeMake(200.0, 5000)
                         lineBreakMode:UILineBreakModeWordWrap];
    if (labelsize.width > 111) {
         text = [[UITextView alloc] initWithFrame:CGRectMake(51, 4, 111, 42)];
    }else{
        text = [[UITextView alloc] initWithFrame:CGRectMake(51, 13, 113, 30)];
    }

     text.userInteractionEnabled = NO;
    text.backgroundColor = [UIColor clearColor];
    text.text = labelStr;
    text.textColor = [UIColor whiteColor];
    text.font = [UIFont systemFontOfSize:13.0f];
    text.textAlignment = NSTextAlignmentLeft;
    [view1 addSubview:img];
    [view1 addSubview:text];
    BMKActionPaopaoView *paopao =[[BMKActionPaopaoView alloc] initWithCustomView:view1] ;
    paopao.tag = 1000 + dex;
    return paopao;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    NSInteger index = view.paopaoView.tag % 1000;
    ReplaceDetailTableViewController*  _detailTable = [[ReplaceDetailTableViewController alloc] init];
    _detailTable.sellerid = [[_tableDataSource objectAtIndex:index] customObjectForkey:@"ID"];
    _detailTable.distance = [[_tableDataSource objectAtIndex:index
                              ] objectForKey:@"SFZ"];

     [self.navigationController pushViewController:_detailTable animated:NO];
}



- (void)didReceiveMemoryWarning {
    NSLog(@"%s",__FUNCTION__);
    [super didReceiveMemoryWarning];

}


@end
